package com.osi.mes.qm.services;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import pnuts.lang.Context;

import com.datasweep.compatibility.client.ATHandler;
import com.datasweep.compatibility.client.ATRow;
import com.datasweep.compatibility.client.ATRowFilter;
import com.datasweep.compatibility.client.DatasweepException;
import com.datasweep.compatibility.client.DsList;
import com.datasweep.compatibility.ui.Time;
import com.osi.mes.base.BaseService;
import com.osi.mes.excel.IBasicTitle;
import com.osi.mes.excel.WriteToExcel;
import com.osi.mes.qm.base.constants.IATGMPChk;
import com.osi.mes.qm.base.constants.IATNames;
import com.osi.mes.qm.base.constants.IBasicConstants;
import com.osi.mes.qm.ftphandler.FTPFilesHandler;
import com.osi.mes.utils.StringUtils;

public class QmGMPChkService extends BaseService {

	private String ftpHost;
	private int ftpPort;
	private String ftpUser;
	private String ftpPassword;

	public QmGMPChkService(Context context) {
		super(context);
	}

	private void initFTPConfig() {
		DsList ftpList = getFunctions()
				.getList(IBasicConstants.FTP_LIST_CONFIG);
		if (ftpList == null)
			return;

		List<String> ftpConfigs = ftpList.getItems();
		if (ftpConfigs == null || ftpConfigs.size() == 0)
			return;

		ftpHost = ftpConfigs.get(0);
		ftpPort = new Integer(ftpConfigs.get(1)).intValue();
		ftpUser = ftpConfigs.get(2);
		ftpPassword = ftpConfigs.get(3);
	}

	public String getFtpHost() {
		return ftpHost;
	}

	public int getFtpPort() {
		return ftpPort;
	}

	public String getFtpUser() {
		return ftpUser;
	}

	public String getFtpPassword() {
		return ftpPassword;
	}

	// 删除GMP项
	public boolean deleteGMPItem(ATRow gmpItem) throws DatasweepException {
		boolean isSucc = true;
		String plName = (String) gmpItem.getValue(IATNames.AT_GMP_ITEM_PL_NAME);
		String wcName = (String) gmpItem.getValue(IATNames.AT_GMP_ITEM_OP_NAME);
		String gmpName = (String) gmpItem.getValue(IATNames.AT_GMP_ITEM_NAME);

		String atDefName = IATNames.AT_GMP_CHK_RESULT;
		ATHandler atHandler = getFunctions().createATHandler(atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(atDefName);
		rowFilter.forColumnNameEqualTo(IATNames.AT_GMP_CHK_RES_PL_NAME, plName);
		rowFilter.forColumnNameEqualTo(IATNames.AT_GMP_CHK_RES_WC_NAME, wcName);
		rowFilter.forColumnNameEqualTo(IATNames.AT_GMP_CHK_RES_GMP_NAME,
				gmpName);

		Vector<ATRow> gmpChkResults = atHandler.getATRowsByFilter(rowFilter,
				false);
		if (gmpChkResults != null) {
			for (int i = 0; i < gmpChkResults.size(); i++) {
				ATRow gmpChkRes = gmpChkResults.get(i);
				isSucc = super.deleteATRow(gmpChkRes);
				if (!isSucc)
					return isSucc;
			}
		}

		isSucc = super.deleteATRow(gmpItem);
		return isSucc;
	}

	// 通过pl,wc,gmp 去查询
	public ATRow getGMPItem(String plName, String wcName, String gmpName)
			throws DatasweepException {
		String atDefName = IATNames.AT_GMP_CHK_ITEM;
		ATHandler atHandler = getFunctions().createATHandler(atDefName);
		ATRowFilter rowFilter = getFunctions().createATRowFilter(atDefName);
		rowFilter.forColumnNameNotEqualTo(IATNames.AT_GMP_ITEM_PL_NAME, plName);
		rowFilter.forColumnNameNotEqualTo(IATNames.AT_GMP_ITEM_OP_NAME, wcName);
		rowFilter.forColumnNameNotEqualTo(IATNames.AT_GMP_ITEM_NAME, gmpName);

		Vector<ATRow> gmpItems = atHandler.getATRowsByFilter(rowFilter, false);
		if (gmpItems == null || gmpItems.size() == 0)
			return null;

		return gmpItems.get(0);
	}

	// 保存GMP的检查结果
	public boolean saveGMPResults(Hashtable<Integer, Vector> values)
			throws DatasweepException {
		if (values == null || values.size() == 0)
			return false;
		String atDefName = IATNames.AT_GMP_CHK_RESULT;
		ATHandler atHandler = getFunctions().createATHandler(atDefName);

		for (int i = 0; i < values.size(); i++) {
			Vector rowData = values.get(i);
			ATRow gmpItem = (ATRow) rowData.get(0);
			int chkResult = new Integer(rowData.get(1).toString()).intValue();

			String chkMark = null;
			if (rowData.get(2) != null)
				chkMark = (String) rowData.get(2);
			String plName = (String) rowData.get(3);
			String wcName = (String) rowData.get(4);

			ATRow atRow = atHandler.createATRow();

			atRow.setValue(AT_GMP_CHK_RES_GMP_NAME,
					gmpItem.getValue(IATGMPChk.AT_GMP_ITEM_NAME));
			// if(IBasicConstants.GMP_CHK_RESULT_DESC_OK.equals(chkResult))
			// atRow.setValue(AT_GMP_CHK_RES_CHECK_RESULT,
			// IBasicConstants.GMP_CHK_RESULT_OK);
			// else
			// if(IBasicConstants.GMP_CHK_RESULT_DESC_NEED_IMPROVE.equals(chkResult))
			// atRow.setValue(AT_GMP_CHK_RES_CHECK_RESULT,
			// IBasicConstants.GMP_CHK_RESULT_NEED_IMPROVE);
			// else
			// if(IBasicConstants.GMP_CHK_RESULT_DESC_NOT.equals(chkResult))
			// atRow.setValue(AT_GMP_CHK_RES_CHECK_RESULT,
			// IBasicConstants.GMP_CHK_RESULT_NOT);
			atRow.setValue(AT_GMP_CHK_RES_CHECK_RESULT, chkResult);
			atRow.setValue(AT_GMP_CHK_RES_MARK, chkMark);
			atRow.setValue(AT_GMP_CHK_RES_CHECK_TIME, getTrxTime());
			atRow.setValue(AT_GMP_CHK_RES_PL_NAME, plName);
			atRow.setValue(AT_GMP_CHK_RES_WC_NAME, wcName);
			atRow.save(getDayStart(), null, null);
		}
		return true;
	}

	public Vector<ATRow> getGMPChkResult(String plName, String wcName,
			Time chkTime) throws DatasweepException {
		ATHandler gmpChkResAtHandler = getFunctions().createATHandler(
				AT_GMP_CHK_RESULT);
		ATRowFilter gmpChkResATRowFilter = getFunctions().createATRowFilter(
				AT_GMP_CHK_RESULT);
		if (chkTime != null) {
			gmpChkResATRowFilter.forColumnNameLessThan(
					AT_GMP_CHK_RES_CHECK_TIME, chkTime.addDays(1));
			gmpChkResATRowFilter.forColumnNameGreaterThanOrEqualTo(
					AT_GMP_CHK_RES_CHECK_TIME, chkTime);
		}

		if (!StringUtils.isNull(plName)) {
			gmpChkResATRowFilter.forColumnNameEqualTo(AT_GMP_CHK_RES_PL_NAME,
					plName);
		}

		if (!StringUtils.isNull(wcName)) {
			gmpChkResATRowFilter.forColumnNameEqualTo(AT_GMP_CHK_RES_WC_NAME,
					wcName);
		}

		Vector<ATRow> gmpChkRes = gmpChkResAtHandler.getATRowsByFilter(
				gmpChkResATRowFilter, false);
		if (gmpChkRes == null || gmpChkRes.size() == 0)
			return new Vector<ATRow>();

		return gmpChkRes;
	}

	public boolean uploadPicsForGMPChkRes(Object[] fileNames, String folder)
			throws Exception {
		if (fileNames == null || fileNames.length == 0)
			return false;

		if (StringUtils.isNull(ftpHost))
			initFTPConfig();

		String[] allFiles = new String[fileNames.length];
		for (int i = 0; i < fileNames.length; i++) {
			allFiles[i] = fileNames[i].toString();
		}

		return FTPFilesHandler.uploadMutiplePics(ftpHost, ftpPort, ftpUser,
				ftpPassword, folder, allFiles, false);
	}

	public void viewFTPFile(String fileFolder) {
		if (StringUtils.isNull(ftpHost))
			initFTPConfig();

		FTPFilesHandler.openFTPToSpecifiedDir(ftpHost, ftpUser, ftpPassword,
				fileFolder);
	}

	public int exportGmpChkResultToExcel(String plName, String wcName,
			Time chkTime, String filePath, String sheetName)
			throws DatasweepException, IOException {
		Vector<ATRow> datas = getGMPChkResult(plName, wcName, chkTime);
		if (datas == null || datas.size() == 0)
			return IBasicConstants.EXPORT_EXCEL_GMP_CHK_NO_DATA;

		makeDescForATRows(datas);
		FileOutputStream fileOut = null;
		try {
			WriteToExcel excel = new WriteToExcel();
			HSSFSheet sheet = excel.createSheet(sheetName);
			String patter = getFunctions().getMessage(
					IBasicConstants.GMP_MESSAGE_NAME,
					IBasicConstants.GMP_MESSAGE_SEARCH_PL)
					+ "{0}    "
					+ getFunctions().getMessage(
							IBasicConstants.GMP_MESSAGE_NAME,
							IBasicConstants.GMP_MESSAGE_SEARCH_WC)
					+ "{1}    "
					+ getFunctions().getMessage(
							IBasicConstants.GMP_MESSAGE_NAME,
							IBasicConstants.GMP_MESSAGE_SEARCH_TIME) + "{2} ";

			String condition = StringUtils.formatMsg(
					patter,
					new Object[] { plName, wcName,
							StringUtils.formatTime(chkTime, "yyyy-MM-dd") });
			excel.createCommonTitle(sheet, IBasicTitle.GMP_CHK_RES_TITLE,
					condition, IBasicTitle.GMP_CHK_RES_COLUMNS);
			excel.createReportBody(sheet, datas,
					IBasicTitle.GMP_CHK_RES_ATROW_KEYS);
			HSSFWorkbook wb = excel.getWorkbook();
			fileOut = new FileOutputStream(filePath);
			wb.write(fileOut);
			fileOut.close();
			return IBasicConstants.EXPORT_EXCEL_GMP_CHK_SUCC;
		} catch (IOException e) {
			throw e;
		} finally {
			if (fileOut != null)
				fileOut.close();
		}
	}

	private void makeDescForATRows(Vector<ATRow> datas) {
		for (int i = 0; i < datas.size(); i++) {
			ATRow atRow = datas.get(i);
			Object checkResObj = atRow
					.getValue(IATGMPChk.AT_GMP_CHK_RES_CHECK_RESULT);
			String checkResDec = "";
			if (checkResObj instanceof Long) {
				int checkRes = ((Long) checkResObj).intValue();
				if (checkRes == IBasicConstants.GMP_CHK_RESULT_OK) {
					checkResDec = getFunctions().getMessage(
							IBasicConstants.GMP_CHK_MESSAGE,
							IBasicConstants.GMP_CHK_MESSAGE_ID_OK);
				} else if (checkRes == IBasicConstants.GMP_CHK_RESULT_NOT) {
					checkResDec = getFunctions().getMessage(
							IBasicConstants.GMP_CHK_MESSAGE,
							IBasicConstants.GMP_CHK_MESSAGE_ID_NOT);
				} else if (checkRes == IBasicConstants.GMP_CHK_RESULT_NEED_IMPROVE) {
					checkResDec = getFunctions().getMessage(
							IBasicConstants.GMP_CHK_MESSAGE,
							IBasicConstants.GMP_CHK_MESSAGE_ID_IMPROVE);
				}
				atRow.setValue(IATGMPChk.AT_GMP_CHK_RES_CHECK_RESULT_DESC,
						checkResDec);
			}

			Object auditStateObj = atRow
					.getValue(IATGMPChk.AT_GMP_CHK_RES_AUDIT_STATE);
			if (auditStateObj instanceof Boolean) {
				Boolean auditState = (Boolean) auditStateObj;
				String auditStateDesc = "";
				if (auditState.booleanValue()) {
					auditStateDesc = getFunctions().getMessage(
							IBasicConstants.GMP_CHK_MESSAGE,
							IBasicConstants.GMP_CHK_MESSAGE_ID_OK);
				} else {
					auditStateDesc = getFunctions().getMessage(
							IBasicConstants.GMP_CHK_MESSAGE,
							IBasicConstants.GMP_CHK_MESSAGE_ID_NOT);
				}
				atRow.setValue(IATGMPChk.AT_GMP_CHK_RES_AUDIT_STATE_DESC,
						auditStateDesc);
			}
		}
	}
}
